package com.winit.openapi.isp.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.common.utils.Dates;
import com.winit.erp.spi.bpartner.BpartnerService;
import com.winit.erp.spi.bpartner.ContractService;
import com.winit.erp.spi.bpartner.command.BpartnerCommand;
import com.winit.erp.spi.bpartner.command.ContractCommand;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.oms.spi.isp.ISPOrderAscanService;
import com.winit.oms.spi.isp.ISPOrderAscanWarehouseService;
import com.winit.oms.spi.isp.ISPOrderTrackingService;
import com.winit.oms.spi.isp.command.order.ISPOrderAscanCreateCommand;
import com.winit.oms.spi.isp.command.order.ISPOrderAscanWarehouseCreateCommand;
import com.winit.oms.spi.isp.vo.ISPOrderAscan;
import com.winit.oms.spi.isp.vo.ISPOrderAscanWarehouse;
import com.winit.oms.spi.isp.vo.ISPOrderTracking;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;
import com.winit.ums.spi.AscanTakeChargeService;
import com.winit.ums.spi.commnad.GetAscanTakeChargeCommand;
import com.winit.ums.spi.vo.AscanTakeCharge;

/**
 * isp 订单轨迹
 * 
 * @author kang.wang 2015-1-5 下午7:52:09
 * @since 1.0
 */
@Controller
@RequestMapping(value = "/ispTrack")
public class ISPOrderTrackController extends BaseController {

	@Resource
	private ISPOrderTrackingService ispOrderTrackingService;
	@Resource
	private ContractService agreementService;
	@Resource
	private ISPOrderAscanService iSPOrderAscanService;
	@Resource
	private AscanTakeChargeService ascanTakeChargeService;
	@Resource
	private BpartnerService bpartnerService;
	@Resource
    private ISPOrderAscanWarehouseService iSPOrderAscanWarehouseService;

	public void setAgreementService(ContractService agreementService) {
		this.agreementService = agreementService;
	}

	/**
	 * @param ispOrderTrackingService
	 *            the ispOrderTrackingService to set
	 */
	public void setIspOrderTrackingService(
			ISPOrderTrackingService ispOrderTrackingService) {
		this.ispOrderTrackingService = ispOrderTrackingService;
	}

	@RequestMapping(value = "/list")
	public String list(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		checkIspRight();
		Object obj = (JSONObject) requestMsg.getData();

		GetByKeyCommand<String> command = new GetByKeyCommand<String>();
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			validOrderNo(json);
			String orderNo = json.getString("orderNo");
			command.setSearchKey(orderNo);
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}
		command.setCtx(CommandContext.getContext());
		// 调用接口查询订单轨迹
		List<ISPOrderTracking> orderTrackingList = ispOrderTrackingService
				.getOrderTrackingList(command);
		if (orderTrackingList != null) {
			List<Map<String, Object>> rsList = buildTrackingList(orderTrackingList);
			responseMsg.setData(rsList);
		}
		return SUCCESS;
	}

	/**
	 * 保存客户ascan时间 
	 * 
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value = "/createISPOrderAscan")
	private String createISPOrderAscan(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {

		Object obj = requestMsg.getData();
		if (obj instanceof JSONObject) {
			Map<String, Object> data = new HashMap<String, Object>();
			JSONObject json = (JSONObject) obj;
			// 校验参数
			ValidateUtil.validNotNull(json, "bpartnerId","卖家id");
			ValidateUtil.validNotNull(json, "takeChargeCode","揽收员员工工号");
			// 校验揽收员代码
			String takeChargeCode = json.getString("takeChargeCode");
			GetAscanTakeChargeCommand acommand = new GetAscanTakeChargeCommand();
			AscanTakeCharge ascanTakeCharge = new AscanTakeCharge();
			ascanTakeCharge.setTakeChargeCode(takeChargeCode);
			acommand.setAscanTakeCharge(ascanTakeCharge);
			ascanTakeCharge = ascanTakeChargeService
					.getAscanTakeChargeByTakeChargeCode(acommand);
			if (ascanTakeCharge.getId() == null) {
				data.put("error", "很抱歉！该工号不存在。如连续输入错误3次，将锁定客户二维码，请核对后重新提交。");
				responseMsg.setData(data);
				return SUCCESS;
			}
			// 保存ascan揽收记录
			Integer bpartnerId = json.getInteger("bpartnerId");
			ISPOrderAscanCreateCommand command = new ISPOrderAscanCreateCommand();
			ISPOrderAscan orderAscan = new ISPOrderAscan();
			orderAscan.setBpartnerId(bpartnerId);
			// Ascan时间
			Date ascanTime = new Date();
			orderAscan.setAscanTime(ascanTime);
			orderAscan.setTakeChargeName(ascanTakeCharge.getTakeChargeName());
			orderAscan.setTakeChargeCode(takeChargeCode);
			command.setOrderAscan(orderAscan);
			iSPOrderAscanService.addOrderAscan(command);
			// 查合作伙伴名称
			BpartnerCommand bCommand = new BpartnerCommand();
			bCommand.setcBpartnerId(bpartnerId.longValue());
			Bpartner bpartner = bpartnerService.queryBpartnerById(bCommand);
			if (bpartner == null) {
				data.put("error", "客户ID不存在！");
				responseMsg.setData(data);
				return SUCCESS;
			}
			// 返回本地时间
			data.put("ascanTime", Dates.getLocalDate(ascanTime));
			data.put("takeChargeName", ascanTakeCharge.getTakeChargeName());
			data.put("customer", bpartner.getName());
			responseMsg.setData(data);
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}
		return SUCCESS;
	}
	
	/**
     * 保存揽收员到仓时间 
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/createISPOrderAscanWarehouse")
    private String createISPOrderAscanWarehouse(@ModelAttribute RequestMsg requestMsg,
            @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            Map<String, Object> data = new HashMap<String, Object>();
            JSONObject json = (JSONObject) obj;
            // 校验参数
            ValidateUtil.validNotNull(json, "warehouseName","仓库名称");
            ValidateUtil.validNotNull(json, "takeChargeCode","揽收员员工工号");
            // 校验揽收员代码
            String takeChargeCode = json.getString("takeChargeCode");
            GetAscanTakeChargeCommand acommand = new GetAscanTakeChargeCommand();
            AscanTakeCharge ascanTakeCharge = new AscanTakeCharge();
            ascanTakeCharge.setTakeChargeCode(takeChargeCode);
            acommand.setAscanTakeCharge(ascanTakeCharge);
            ascanTakeCharge = ascanTakeChargeService
                    .getAscanTakeChargeByTakeChargeCode(acommand);
            if (ascanTakeCharge.getId() == null) {
                data.put("error", "很抱歉！该工号不存在。");
                responseMsg.setData(data);
                return SUCCESS;
            }
            // 保存到仓时间
            String warehouseName = json.getString("warehouseName");
            ISPOrderAscanWarehouseCreateCommand command = new ISPOrderAscanWarehouseCreateCommand();
            ISPOrderAscanWarehouse orderAscanWarehouse = new ISPOrderAscanWarehouse();
            orderAscanWarehouse.setWarehouseName(warehouseName);
            // 到仓时间
            Date toWarehouseTime = new Date();
            orderAscanWarehouse.setToWarehouseTime(toWarehouseTime);
            orderAscanWarehouse.setTakeChargeName(ascanTakeCharge.getTakeChargeName());
            orderAscanWarehouse.setTakeChargeCode(takeChargeCode);
            command.setOrderAscanWarehouse(orderAscanWarehouse);
            iSPOrderAscanWarehouseService.addOrderAscanWarehouse(command);
            // 返回本地时间
            data.put("toWarehouseTime", Dates.getLocalDate(toWarehouseTime));
            data.put("takeChargeName", ascanTakeCharge.getTakeChargeName());
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
	

	private List<Map<String, Object>> buildTrackingList(
			List<ISPOrderTracking> orderTrackingList) {
		List<Map<String, Object>> rsList = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		for (ISPOrderTracking t : orderTrackingList) {
			map = new HashMap<String, Object>();
			map.put("operateTime", DateUtil.parse2String(t.getTrackingDate(),
					DateUtil.FULL_DATE_STRING));
			map.put("operateLocation", t.getTrackingAddr());
			map.put("operateDesc", t.getTrackingMsg());
			rsList.add(map);
		}
		return rsList;
	}

	private void validOrderNo(JSONObject json) {
		// orderNo
		ValidateUtil.validNotNull(json, "orderNo");
		ValidateUtil.validMaxLength(json, "orderNo", 60);
	}

	// 效验用户是不是isp用户
	public void checkIspRight() {
		ContractCommand command = new ContractCommand();
		command.setBusiType("ISP");
		command.setBpartnerId(Long.parseLong(CommandContext.getContext()
				.getUserId()));
		boolean rightStatus = agreementService.isOpenContract(command);

		if (!rightStatus) {
			throw new ApiException(ErrorCode.USERNAME_ISNOT_ISP_USER);
		}

	}
}
